#include <stdio.h>
#include <string.h>
#include <openssl/evp.h>
#include <openssl/pem.h>

int main() {
    const char *msg = "fsl";
    const char *id = "1234567812345678";

    // 读取公钥
    FILE *fp = fopen("sm2public_key.pem", "r");
    EVP_PKEY *pkey = PEM_read_PUBKEY(fp, NULL, NULL, NULL);
    fclose(fp);
    if (!pkey) { fprintf(stderr, "Load public key failed\n"); return 1; }

    // 读取签名
    FILE *sig_fp = fopen("sm2.sig", "rb");
    if (!sig_fp) { fprintf(stderr, "Signature file not found. Run sm2_sign first.\n"); EVP_PKEY_free(pkey); return 1; }
    fseek(sig_fp, 0, SEEK_END);
    size_t sig_len = ftell(sig_fp);
    rewind(sig_fp);
    unsigned char *sig = malloc(sig_len);
    fread(sig, 1, sig_len, sig_fp);
    fclose(sig_fp);

    // 验签
    EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
    EVP_PKEY_CTX *pctx;
    int ret = (EVP_DigestVerifyInit(md_ctx, &pctx, EVP_sm3(), NULL, pkey) > 0 &&
               EVP_PKEY_CTX_set_ec_scheme(pctx, NID_sm2) > 0 &&
               EVP_PKEY_CTX_set1_id(pctx, (unsigned char*)id, strlen(id)) > 0 &&
               EVP_DigestVerifyUpdate(md_ctx, msg, strlen(msg)) > 0 &&
               EVP_DigestVerifyFinal(md_ctx, sig, sig_len) > 0);

    EVP_MD_CTX_free(md_ctx); EVP_PKEY_free(pkey); free(sig);

    if (ret) {
        printf("SM2 verify: success\n");
    } else {
        printf("SM2 verify: failed\n");
        return 1;
    }
    return 0;
}
